import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)
import vuexPersist from "vuex-persist";
export default new Vuex.Store({
  state: {
    localGoodsData: []
  },
  mutations: {
    addGoods(state, val) {
      let flag = false
      state.localGoodsData.forEach(item => {
        if (item.id == val.id) {
          flag = true
          item.num++
        }
      })
      if (!flag) {
        state.localGoodsData.push(val)
      }
    },
    // 全部删除
    clear(state) {
      state.localGoodsData = []
    },
    // 减少商品
    subGoods(state, value) {
      state.localGoodsData.forEach((element, index) => {
        if (element.id == value.id) {
          element.num <= 0 ? 0 : element.num--;
          if (element.num <= 0) {
            state.localGoodsData.splice(index,1)
          }
        }
      });
    },
    // 删除
    remove(state, value) {
      state.localGoodsData = state.localGoodsData.filter(item => item.id != value)
      console.log(1);
    },
    changeNum() {}
  },
  actions: {},
  modules: {},
  getters: {
    totalNum(state) {
      return state.localGoodsData.reduce((num, item) => num += item.num * item.price, 0)
    },
    subTotal(state) {
      return state.localGoodsData.reduce((num, item) => num += item.num, 0)
    },
  },
  // plugins: [
  //   new vuexPersist({
  //     storage: window.localStorage,
  //   }).plugin,
  // ],
})